<template>
  <div class="sales-orders-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>销售订单</h3>
          <div class="header-actions">
            <ExportButton 
              :data="tableData" 
              :columns="exportColumns" 
              filename="销售订单"
              data-type="orders"
              @export="handleExport"
            />
            <el-button type="primary" @click="showAddDialog">
              <el-icon><Plus /></el-icon>
              新建订单
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="订单号">
            <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" clearable />
          </el-form-item>
          <el-form-item label="客户">
            <el-select v-model="searchForm.customerId" placeholder="请选择客户" clearable>
              <el-option 
                v-for="customer in customers" 
                :key="customer.id" 
                :label="customer.name" 
                :value="customer.id" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="待确认" value="待确认" />
              <el-option label="待审批" value="待审批" />
              <el-option label="已确认" value="已确认" />
              <el-option label="待发货" value="待发货" />
              <el-option label="已发货" value="已发货" />
              <el-option label="已完成" value="已完成" />
              <el-option label="已开票" value="已开票" />
              <el-option label="已取消" value="已取消" />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="orderNo" label="订单号" width="150" />
        <el-table-column prop="customerName" label="客户" width="150" />
        <el-table-column prop="totalAmount" label="订单金额" width="120">
          <template #default="{ row }">
            ¥{{ row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="expectedDate" label="预计发货" width="120" />
        <el-table-column prop="salesman" label="销售员" width="100" />
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button 
              v-if="row.status === '待确认'" 
              type="success" 
              size="small" 
              @click="handleConfirm(row)"
            >
              确认
            </el-button>
            <el-button 
              v-if="row.status === '待审批'" 
              type="warning" 
              size="small" 
              @click="handleApprove(row)"
            >
              审批
            </el-button>
            <el-button 
              v-if="['已确认', '待发货'].includes(row.status)" 
              type="info" 
              size="small" 
              @click="handleShip(row)"
            >
              发货
            </el-button>
            <el-button 
              v-if="row.status === '已发货'" 
              type="success" 
              size="small" 
              @click="handleComplete(row)"
            >
              完成
            </el-button>
            <el-button 
              v-if="['待确认', '已确认', '待审批'].includes(row.status)" 
              type="danger" 
              size="small" 
              @click="handleCancel(row)"
            >
              取消
            </el-button>
            <el-button 
              v-if="row.status === '已完成'" 
              type="primary" 
              size="small" 
              @click="handleInvoice(row)"
            >
              开票
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑订单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="1000px"
      @close="handleDialogClose"
    >
      <el-form
        ref="orderFormRef"
        :model="orderForm"
        :rules="orderRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单号" prop="orderNo">
              <el-input v-model="orderForm.orderNo" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户" prop="customerId">
              <el-select v-model="orderForm.customerId" placeholder="请选择客户" style="width: 100%" @change="handleCustomerChange">
                <el-option 
                  v-for="customer in customers" 
                  :key="customer.id" 
                  :label="customer.name" 
                  :value="customer.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预计发货" prop="expectedDate">
              <el-date-picker
                v-model="orderForm.expectedDate"
                type="date"
                placeholder="请选择预计发货日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售员" prop="salesman">
              <el-input v-model="orderForm.salesman" placeholder="请输入销售员" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="orderForm.remark" 
            type="textarea" 
            :rows="2"
            placeholder="请输入备注信息" 
          />
        </el-form-item>

        <el-form-item label="需要审批" prop="needApproval">
          <el-switch 
            v-model="orderForm.needApproval" 
            active-text="是" 
            inactive-text="否"
          />
        </el-form-item>

        <el-form-item 
          v-if="orderForm.needApproval" 
          label="审批原因" 
          prop="approvalReason"
        >
          <el-input 
            v-model="orderForm.approvalReason" 
            type="textarea" 
            :rows="2"
            placeholder="请输入需要审批的原因" 
          />
        </el-form-item>

        <!-- 商品明细 -->
        <el-form-item label="商品明细">
          <div class="product-list">
            <div class="product-header">
              <el-button type="primary" size="small" @click="addProduct">
                <el-icon><Plus /></el-icon>
                添加商品
              </el-button>
            </div>
            <el-table :data="orderForm.products" border>
              <el-table-column prop="productCode" label="商品编码" width="120">
                <template #default="{ row, $index }">
                  <el-input v-model="row.productCode" placeholder="商品编码" />
                </template>
              </el-table-column>
              <el-table-column prop="productName" label="商品名称" width="200">
                <template #default="{ row, $index }">
                  <el-input v-model="row.productName" placeholder="商品名称" />
                </template>
              </el-table-column>
              <el-table-column prop="specification" label="规格" width="150">
                <template #default="{ row, $index }">
                  <el-input v-model="row.specification" placeholder="规格" />
                </template>
              </el-table-column>
              <el-table-column prop="unit" label="单位" width="80">
                <template #default="{ row, $index }">
                  <el-input v-model="row.unit" placeholder="单位" />
                </template>
              </el-table-column>
              <el-table-column prop="quantity" label="数量" width="100">
                <template #default="{ row, $index }">
                  <el-input-number 
                    v-model="row.quantity" 
                    :min="1" 
                    style="width: 100%"
                    @change="calculateAmount"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="unitPrice" label="单价" width="100">
                <template #default="{ row, $index }">
                  <el-input-number 
                    v-model="row.unitPrice" 
                    :min="0" 
                    :precision="2"
                    style="width: 100%"
                    @change="calculateAmount"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="amount" label="金额" width="100">
                <template #default="{ row }">
                  ¥{{ (row.quantity * row.unitPrice).toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ $index }">
                  <el-button type="danger" size="small" @click="removeProduct($index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="total-amount">
              <span>订单总额：<strong>¥{{ orderForm.totalAmount.toFixed(2) }}</strong></span>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="订单详情"
      width="800px"
    >
      <div v-if="currentOrder">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ currentOrder.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="客户">{{ currentOrder.customerName }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ currentOrder.totalAmount.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentOrder.status)">{{ currentOrder.status }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentOrder.createTime }}</el-descriptions-item>
          <el-descriptions-item label="预计发货">{{ currentOrder.expectedDate }}</el-descriptions-item>
          <el-descriptions-item label="销售员">{{ currentOrder.salesman }}</el-descriptions-item>
          <el-descriptions-item label="审批状态">
            <el-tag :type="currentOrder.approvalStatus === '已审批' ? 'success' : currentOrder.approvalStatus === '已拒绝' ? 'danger' : 'warning'">
              {{ currentOrder.approvalStatus || '无需审批' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="审批时间">{{ currentOrder.approvalTime || '-' }}</el-descriptions-item>
          <el-descriptions-item label="审批人">{{ currentOrder.approver || '-' }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ currentOrder.remark || '-' }}</el-descriptions-item>
        </el-descriptions>

        <el-divider>商品明细</el-divider>
        <el-table :data="currentOrder.products" border>
          <el-table-column prop="productCode" label="商品编码" width="120" />
          <el-table-column prop="productName" label="商品名称" width="200" />
          <el-table-column prop="specification" label="规格" width="150" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column prop="unitPrice" label="单价" width="100">
            <template #default="{ row }">
              ¥{{ row.unitPrice.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="金额" width="100">
            <template #default="{ row }">
              ¥{{ (row.quantity * row.unitPrice).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete, View } from '@element-plus/icons-vue'
import ExportButton from '@/components/common/ExportButton.vue'
import { getDefaultColumns } from '@/utils/export'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const submitLoading = ref(false)
const orderFormRef = ref()

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  customerId: '',
  status: '',
  dateRange: []
})

// 订单表单
const orderForm = reactive({
  id: null,
  orderNo: '',
  customerId: '',
  customerName: '',
  totalAmount: 0,
  expectedDate: '',
  salesman: '',
  remark: '',
  needApproval: false,
  approvalReason: '',
  products: []
})

// 表单验证规则
const orderRules = {
  customerId: [
    { required: true, message: '请选择客户', trigger: 'change' }
  ],
  expectedDate: [
    { required: true, message: '请选择预计发货日期', trigger: 'change' }
  ],
  salesman: [
    { required: true, message: '请输入销售员', trigger: 'blur' }
  ]
}

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 客户数据
const customers = ref([
  { id: 1, name: '张三', code: 'C001' },
  { id: 2, name: '北京科技有限公司', code: 'C002' },
  { id: 3, name: '王总', code: 'C003' }
])

// 表格数据
const tableData = ref([
  {
    id: 1,
    orderNo: 'SO20240115001',
    customerId: 1,
    customerName: '张三',
    totalAmount: 15000,
    status: '已完成',
    createTime: '2024-01-15 10:00:00',
    expectedDate: '2024-01-16',
    salesman: '销售员A',
    remark: 'VIP客户',
    approvalStatus: '已审批',
    approvalTime: '2024-01-15 10:30:00',
    approver: '经理A',
    products: [
      {
        productCode: 'P001',
        productName: 'iPhone 15',
        specification: '128GB 黑色',
        unit: '台',
        quantity: 3,
        unitPrice: 5000
      }
    ]
  },
  {
    id: 2,
    orderNo: 'SO20240115002',
    customerId: 2,
    customerName: '北京科技有限公司',
    totalAmount: 8500,
    status: '待发货',
    createTime: '2024-01-15 14:00:00',
    expectedDate: '2024-01-18',
    salesman: '销售员B',
    remark: '',
    approvalStatus: '已审批',
    approvalTime: '2024-01-15 14:30:00',
    approver: '经理B',
    products: [
      {
        productCode: 'P002',
        productName: 'MacBook Pro',
        specification: '13英寸 M2芯片',
        unit: '台',
        quantity: 1,
        unitPrice: 8500
      }
    ]
  },
  {
    id: 3,
    orderNo: 'SO20240115003',
    customerId: 3,
    customerName: '王总',
    totalAmount: 25000,
    status: '待审批',
    createTime: '2024-01-15 16:00:00',
    expectedDate: '2024-01-20',
    salesman: '销售员C',
    remark: '大客户订单',
    approvalStatus: '待审批',
    approvalTime: '',
    approver: '',
    products: [
      {
        productCode: 'P001',
        productName: 'iPhone 15',
        specification: '256GB 白色',
        unit: '台',
        quantity: 5,
        unitPrice: 5000
      }
    ]
  }
])

const currentOrder = ref(null)

// 导出列配置
const exportColumns = getDefaultColumns('orders')

// 计算属性
const isEdit = computed(() => !!orderForm.id)
const dialogTitle = computed(() => isEdit.value ? '编辑订单' : '新建订单')

// 方法
const loadData = () => {
  loading.value = true
  setTimeout(() => {
    pagination.total = tableData.value.length
    loading.value = false
  }, 500)
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    orderNo: '',
    customerId: '',
    status: '',
    dateRange: []
  })
  handleSearch()
}

const showAddDialog = () => {
  dialogVisible.value = true
  resetForm()
  generateOrderNo()
}

const handleEdit = (row) => {
  dialogVisible.value = true
  Object.assign(orderForm, { ...row })
}

const handleView = (row) => {
  currentOrder.value = row
  viewDialogVisible.value = true
}

const handleConfirm = async (row) => {
  try {
    await ElMessageBox.confirm('确定要确认该订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value[index].status = '已确认'
      ElMessage.success('订单确认成功')
      loadData()
    }
  } catch {
    // 用户取消操作
  }
}

const handleShip = async (row) => {
  try {
    await ElMessageBox.confirm('确定要发货该订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value[index].status = '已发货'
      ElMessage.success('订单发货成功')
      loadData()
    }
  } catch {
    // 用户取消操作
  }
}

const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value[index].status = '已取消'
      ElMessage.success('订单取消成功')
      loadData()
    }
  } catch {
    // 用户取消操作
  }
}

const handleApprove = async (row) => {
  try {
    await ElMessageBox.confirm('确定要审批通过该订单吗？', '审批确认', {
      confirmButtonText: '通过',
      cancelButtonText: '拒绝',
      type: 'warning'
    })
    
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value[index].status = '已确认'
      tableData.value[index].approvalStatus = '已审批'
      tableData.value[index].approvalTime = new Date().toLocaleString()
      tableData.value[index].approver = '当前用户'
      ElMessage.success('订单审批通过')
      loadData()
    }
  } catch {
    // 用户选择拒绝
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value[index].status = '已取消'
      tableData.value[index].approvalStatus = '已拒绝'
      tableData.value[index].approvalTime = new Date().toLocaleString()
      tableData.value[index].approver = '当前用户'
      ElMessage.warning('订单审批拒绝')
      loadData()
    }
  }
}

const handleComplete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要完成该订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value[index].status = '已完成'
      ElMessage.success('订单完成成功')
      loadData()
    }
  } catch {
    // 用户取消操作
  }
}

const handleInvoice = async (row) => {
  try {
    await ElMessageBox.confirm('确定要开具发票吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value[index].status = '已开票'
      ElMessage.success('发票开具成功')
      loadData()
    }
  } catch {
    // 用户取消操作
  }
}

const handleCustomerChange = (customerId) => {
  const customer = customers.value.find(c => c.id === customerId)
  if (customer) {
    orderForm.customerName = customer.name
  }
}

const addProduct = () => {
  orderForm.products.push({
    productCode: '',
    productName: '',
    specification: '',
    unit: '',
    quantity: 1,
    unitPrice: 0
  })
}

const removeProduct = (index) => {
  orderForm.products.splice(index, 1)
  calculateAmount()
}

const calculateAmount = () => {
  orderForm.totalAmount = orderForm.products.reduce((total, product) => {
    return total + (product.quantity * product.unitPrice)
  }, 0)
}

const generateOrderNo = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const random = String(Math.floor(Math.random() * 1000)).padStart(3, '0')
  orderForm.orderNo = `SO${year}${month}${day}${random}`
}

const getStatusType = (status) => {
  const statusMap = {
    '待确认': 'warning',
    '待审批': 'warning',
    '已确认': 'primary',
    '待发货': 'info',
    '已发货': 'success',
    '已完成': 'success',
    '已开票': 'success',
    '已取消': 'danger'
  }
  return statusMap[status] || 'info'
}

const handleSubmit = async () => {
  if (!orderFormRef.value) return

  try {
    await orderFormRef.value.validate()
    
    if (orderForm.products.length === 0) {
      ElMessage.warning('请至少添加一个商品')
      return
    }

    submitLoading.value = true

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    if (isEdit.value) {
      // 编辑订单
      const index = tableData.value.findIndex(item => item.id === orderForm.id)
      if (index > -1) {
        tableData.value[index] = { ...orderForm }
      }
      ElMessage.success('编辑成功')
    } else {
      // 新增订单
      const newOrder = {
        ...orderForm,
        id: Date.now(),
        status: orderForm.needApproval ? '待审批' : '待确认',
        createTime: new Date().toLocaleString(),
        approvalStatus: orderForm.needApproval ? '待审批' : '无需审批',
        approvalTime: '',
        approver: ''
      }
      tableData.value.unshift(newOrder)
      ElMessage.success('新建成功')
    }

    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  resetForm()
}

const resetForm = () => {
  Object.assign(orderForm, {
    id: null,
    orderNo: '',
    customerId: '',
    customerName: '',
    totalAmount: 0,
    expectedDate: '',
    salesman: '',
    remark: '',
    needApproval: false,
    approvalReason: '',
    products: []
  })
  orderFormRef.value?.clearValidate()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

const handleExport = (exportInfo) => {
  console.log('导出完成:', exportInfo)
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.sales-orders-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.product-list {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

.product-header {
  margin-bottom: 10px;
}

.total-amount {
  margin-top: 10px;
  text-align: right;
  font-size: 16px;
  color: #e6a23c;
}
</style>
